'use client';

import type { FlowVO } from '@/app/api/flows/route';
import { MarkdownRender } from '@/components/common/MarkdownRender';
import FlowCreateForm from '@/components/flows/FlowCreateForm';
import type { PaginatedResult } from '@/libs/pagination';
import { handleAddFlow } from '@/services/flow';
import { clientFetch } from '@/utils/request';
import {
  Button,
  Card,
  Image,
  Input,
  Modal,
  Space,
  Table,
  Tag,
  Typography,
  Toast,
  Popconfirm,
} from '@douyinfe/semi-ui';
import { Icon } from '@iconify/react';
import React, { useState } from 'react';
import useSWR from 'swr';
import { useDebounceValue } from 'usehooks-ts';

const { Title, Text } = Typography;

export default function FlowPage() {
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [visable, setVisable] = useState(false);
  const [modalContent, setModalContent] = useState<string>('');

  // 添加工艺流程相关状态
  const [addModalVisible, setAddModalVisible] = useState(false);

  // 编辑相关状态
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editingFlow, setEditingFlow] = useState<FlowVO | null>(null);

  // 删除相关状态
  const [deleteLoading, setDeleteLoading] = useState<string | null>(null);

  const [searchTerm, setSearchTerm] = useState('');
  const debouncedSearchTerm = useDebounceValue(searchTerm, 500);

  const params = new URLSearchParams({
    page: `${currentPage}`,
    pageSize: `${pageSize}`,
    ...(searchTerm && { search: debouncedSearchTerm[0] }),
  });

  const fetcher = async () => {
    const res = await clientFetch.get<PaginatedResult<FlowVO>>(
      `/api/flows?${params.toString()}`,
      {
        params,
      }
    );

    if (res.code !== 200) {
      throw new Error(res.message || '请求失败');
    }

    return res.data;
  };

  const { data, isLoading, mutate } = useSWR(
    `/api/flows?${params.toString()}`,
    fetcher
  );

  // 处理编辑
  const handleEditClick = (record: FlowVO): void => {
    setEditingFlow(record);
    setEditModalVisible(true);
  };

  // 处理删除
  const handleDeleteClick = async (record: FlowVO): Promise<void> => {
    setDeleteLoading(record._id);

    try {
      const res = await clientFetch.delete(`/api/flows`, {
        params: {
          id: record._id,
        },
      });

      if (res.code !== 200) {
        throw new Error(res.message || '删除失败');
      }

      Toast.success('删除成功');
      // 重新获取数据
      mutate();
    } catch (error) {
      Toast.error(error instanceof Error ? error.message : '删除失败');
    } finally {
      setDeleteLoading(null);
    }
  };

  // 定义表格列
  const columns = [
    {
      title: (
        <div className="flex items-center gap-2">
          <Icon icon="carbon:code" className="h-4 w-4 text-blue-500" />
          <span className="font-semibold">工艺编码</span>
        </div>
      ),
      dataIndex: 'code',
      key: 'processCode',
      width: 140,
      fixed: 'left' as const,
      render: (text: string) => (
        <div className="flex items-center gap-2">
          <div className="h-2 w-2 rounded-full bg-blue-500"></div>
          <Text
            strong
            className="rounded-md border border-blue-100 bg-blue-50 px-2 py-1 font-mono text-sm text-blue-600"
          >
            {text}
          </Text>
        </div>
      ),
    },
    {
      title: (
        <div className="flex items-center gap-2">
          <Icon icon="tabler:file-text" className="h-4 w-4 text-green-500" />
          <span className="font-semibold">工艺简称</span>
        </div>
      ),
      dataIndex: 'name',
      key: 'description',
      width: 160,
      render: (text: string) => (
        <div className="py-1">
          {text ? (
            <Tag
              color="green"
              size="large"
              className="rounded-full px-3 py-1 font-medium"
            >
              {text}
            </Tag>
          ) : (
            <Text type="tertiary" className="italic">
              暂无简称
            </Text>
          )}
        </div>
      ),
    },
    {
      title: (
        <div className="flex items-center gap-2">
          <Icon icon="ph:image" className="h-4 w-4 text-purple-500" />
          <span className="font-semibold">工艺图</span>
        </div>
      ),
      dataIndex: 'imageUrl',
      key: 'image',
      width: 120,
      render: (url: string) => (
        <div className="flex justify-center py-2">
          <div className="group relative">
            <Image
              src={url}
              alt="工艺图"
              width={'auto'}
              height={'100%'}
              className="rounded-lg border-2 border-gray-200 shadow-sm transition-all duration-200 group-hover:border-blue-300 group-hover:shadow-md"
            />
          </div>
        </div>
      ),
    },
    {
      title: (
        <div className="flex items-center gap-2">
          <Icon
            icon="material-symbols:info-outline"
            className="h-4 w-4 text-orange-500"
          />
          <span className="font-semibold">详情信息</span>
        </div>
      ),
      dataIndex: 'aiAnalysisText',
      key: 'param1',
      width: 300,
      render: (text: string) => (
        <div
          className="py-2"
          onClick={() => {
            setVisable(true);
            setModalContent(text);
          }}
        >
          <div className="cursor-pointer rounded-lg border border-gray-200 bg-gradient-to-r from-gray-50 to-gray-100 p-3 transition-all duration-200 hover:border-orange-300">
            <MarkdownRender
              content={text}
              className="max-h-[80px] overflow-hidden text-ellipsis bg-transparent text-sm leading-relaxed"
            />
            <div className="mt-2 flex items-center gap-1 text-xs text-gray-500">
              <Icon icon="carbon:view" className="h-3 w-3" />
              <span>点击查看完整内容</span>
            </div>
          </div>
        </div>
      ),
    },
    {
      title: (
        <div className="flex items-center gap-2">
          <Icon
            icon="material-symbols:settings"
            className="h-4 w-4 text-gray-500"
          />
          <span className="font-semibold">操作</span>
        </div>
      ),
      key: 'actions',
      width: 160,
      fixed: 'right' as const,
      render: (_: any, record: FlowVO) => (
        <div className="flex items-center gap-2">
          <Button
            type="tertiary"
            icon={<Icon icon="lucide:edit" className="h-3 w-3" />}
            onClick={() => handleEditClick(record)}
            className="text-blue-600 hover:bg-blue-50"
          >
            编辑
          </Button>
          <Popconfirm
            title="确认删除"
            content="删除后无法恢复，确定要删除这条工艺流程吗？"
            onConfirm={() => handleDeleteClick(record)}
            position="topRight"
          >
            <Button
              type="danger"
              theme="borderless"
              icon={<Icon icon="lucide:trash-2" className="h-3 w-3" />}
              loading={deleteLoading === record._id}
              className="text-red-600 hover:bg-red-50"
            >
              删除
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  const handleSearchChange = (value: string): void => {
    setSearchTerm(value);
    setCurrentPage(1);
  };

  const handleAddFlowClick = (): void => {
    setAddModalVisible(true);
  };

  return (
    <div className="min-h-screen bg-gray-50 p-6">
      <Card className="mb-4">
        <Title className="mb-4" heading={4}>
          工艺流程管理
        </Title>

        <Space wrap className="mb-4">
          <Input
            prefix={<Icon icon="mynaui:search" className="m-2 h-4 w-4" />}
            placeholder="搜索工艺编码、简称"
            value={searchTerm}
            onChange={handleSearchChange}
            className="w-[300px]"
            showClear
          />

          <Button
            icon={<Icon icon="lucide:plus" className="h-4 w-4" />}
            onClick={handleAddFlowClick}
            type="primary"
          >
            添加工艺流程
          </Button>

          <Text type="tertiary">共 {data?.pagination.total || 0} 条记录</Text>
        </Space>
      </Card>

      <Card className="overflow-hidden border-0 bg-white/90 shadow-xl backdrop-blur-sm">
        <Table
          columns={columns}
          dataSource={data?.data}
          rowKey="_id"
          pagination={{
            pageSize: pageSize,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: false,
            defaultCurrentPage: 1,
            currentPage: currentPage,
            onPageChange(currentPage: number) {
              setCurrentPage(currentPage);
            },
            total: data?.pagination.total,
            onPageSizeChange(newPageSize: number) {
              setPageSize(newPageSize);
            },
          }}
          scroll={{
            x: 1000,
            y: 1200,
          }}
          bordered
          size="small"
          loading={isLoading}
          empty="暂无数据"
        />
      </Card>

      {/* 原有的详情信息模态框 */}
      <Modal
        width={800}
        visible={visable}
        onCancel={() => setVisable(false)}
        footer={null}
        title={
          <div className="flex items-center gap-2">
            <Icon
              icon="material-symbols:info-outline"
              className="h-5 w-5 text-orange-500"
            />
            <span>详情信息</span>
          </div>
        }
      >
        <MarkdownRender
          content={modalContent}
          className="max-h-[70vh] overflow-y-auto py-4"
        ></MarkdownRender>
      </Modal>

      {/* 添加工艺流程模态框 */}
      <Modal
        visible={addModalVisible}
        title={
          <div className="flex items-center gap-2">
            <Icon icon="lucide:plus-circle" className="h-5 w-5 text-blue-500" />
            <span>添加工艺流程</span>
          </div>
        }
        onCancel={() => {
          setAddModalVisible(false);
        }}
        footer={null}
        width={600}
        className="add-flow-modal"
      >
        <FlowCreateForm
          onSuccess={() => {
            setAddModalVisible(false);
            mutate(); // 刷新数据
          }}
          onClose={() => {
            setAddModalVisible(false);
          }}
          onSubmit={async (values: any) => {
            const res = await handleAddFlow(values);

            if (res.code !== 201) {
              Toast.error('创建失败');
              return;
            }

            Toast.success('创建成功');
            setAddModalVisible(false);

            mutate(); // 刷新数据
          }}
        />
      </Modal>

      {/* 编辑工艺流程模态框 */}
      <Modal
        visible={editModalVisible}
        title={
          <div className="flex items-center gap-2">
            <Icon icon="lucide:edit" className="h-5 w-5 text-green-500" />
            <span>编辑工艺流程</span>
          </div>
        }
        onCancel={() => {
          setEditModalVisible(false);
          setEditingFlow(null);
        }}
        footer={null}
        width={600}
        className="edit-flow-modal"
      >
        <FlowCreateForm
          editData={editingFlow}
          onSuccess={() => {
            setEditModalVisible(false);
            setEditingFlow(null);
            mutate();
          }}
          onClose={() => {
            setEditModalVisible(false);
          }}
          onSubmit={() => {}}
        />
      </Modal>
    </div>
  );
}
